package com.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.CouponSaleDetail;
import com.finance.mapper.CouponSaleDetailMapper;
import com.finance.service.CouponSaleDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C19
 * 优惠券销售明细数据Service实现类
 */
@Slf4j
@Service
public class CouponSaleDetailServiceImpl extends ServiceImpl<CouponSaleDetailMapper, CouponSaleDetail> implements CouponSaleDetailService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records) {
        return processOrders(records, null, false, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            return 0;
        }

        // 如果强制更新，先删除指定日期和影院ID的数据
        if (forceUpdate) {
            LambdaQueryWrapper<CouponSaleDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CouponSaleDetail::getSearchDate, searchDate)
                  .eq(CouponSaleDetail::getCinemaId, cinemaId);
            this.remove(wrapper);
        }

        List<CouponSaleDetail> details = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                CouponSaleDetail detail = new CouponSaleDetail();
                detail.setCinemaId(cinemaId);
                //销售时间,销售单号,订单号,销售类型,适用商品,券类型,券模版名称,券自定义分类
                String saleTime = record.get("销售时间");
                if (StringUtils.hasText(saleTime)) {
                    detail.setSaleTime(LocalDateTime.parse(saleTime, DATE_TIME_FORMATTER));
                }
                if (StringUtils.hasText(record.get("销售单号"))) {
                    detail.setSaleNo(record.get("销售单号"));
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    detail.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("销售类型"))) {
                    detail.setSaleType(record.get("销售类型"));
                }
                if (StringUtils.hasText(record.get("适用商品"))) {
                    detail.setApplicableGoods(record.get("适用商品"));
                }
                if (StringUtils.hasText(record.get("券类型"))) {
                    detail.setCouponType(record.get("券类型"));
                }
                if (StringUtils.hasText(record.get("券模版名称"))) {
                    detail.setCouponTemplateName(record.get("券模版名称"));
                }
                if (StringUtils.hasText(record.get("券自定义分类"))) {
                    detail.setCouponCustomCategory(record.get("券自定义分类"));
                }
                // 券售价（元）,券数量,券销售总额（元）,实收金额（元）
                String productPrice = record.get("券售价（元）");
                if (StringUtils.hasText(productPrice)) {
                    detail.setCouponPrice(new BigDecimal(productPrice));
                }
                // 转换券数量
                String quantity = record.get("券数量");
                if (StringUtils.hasText(quantity)) {
                    detail.setCouponQuantity(Integer.parseInt(quantity));
                }
                // 转换券销售总额
                String totalSale = record.get("券销售总额（元）");
                if (StringUtils.hasText(totalSale)) {
                    detail.setTotalSaleAmount(new BigDecimal(totalSale));
                }
                // 转换实收金额
                String actualAmount = record.get("实收金额（元）");
                if (StringUtils.hasText(actualAmount)) {
                    detail.setActualAmount(new BigDecimal(actualAmount));
                }
                // 收款方,支付工具编码,支付工具,客户名称,券码有效期,销售员,销售员工号
                if (StringUtils.hasText(record.get("收款方"))) {
                    detail.setPayee(record.get("收款方"));
                }
                if (StringUtils.hasText(record.get("支付工具编码"))) {
                    detail.setPaymentToolCode(record.get("支付工具编码"));
                }
                if (StringUtils.hasText(record.get("支付工具"))) {
                    detail.setPaymentTool(record.get("支付工具"));
                }
                if (StringUtils.hasText(record.get("客户名称"))) {
                    detail.setCustomerName(record.get("客户名称"));
                }
                if (StringUtils.hasText(record.get("券码有效期"))) {
                    detail.setCouponValidityPeriod(record.get("券码有效期"));
                }
                if (StringUtils.hasText(record.get("销售员"))) {
                    detail.setSalesperson(record.get("销售员"));
                }
                if (StringUtils.hasText(record.get("销售员工号"))) {
                    detail.setSalespersonNo(record.get("销售员工号"));
                }
                detail.setSearchDate(searchDate);
                // 设置新增字段
                if (StringUtils.hasText(record.get("收款方影城编码"))) {
                    detail.setPayeeCinemaCode(record.get("收款方影城编码"));
                }
                if (StringUtils.hasText(record.get("客户外部编码"))) {
                    detail.setCustomerExternalCode(record.get("客户外部编码"));
                }

                details.add(detail);
            } catch (Exception e) {
                log.error("Error processing coupon sale record: {}", record, e);
                throw new RuntimeException("Failed to process coupon sale record", e);
            }
        }
        try {
            saveBatch(details);
            return details.size();
        } catch (Exception e) {
            log.error("Error saving coupon sale data batch", e);
            throw new RuntimeException("Failed to save coupon sale data batch", e);
        }
    }
}